package sz.szsmk.citizencard.mvp.presenter;

import android.util.Log;

import com.google.gson.Gson;

import org.jetbrains.annotations.Nullable;

import java.util.Objects;

import javax.inject.Inject;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.RxSubscribers;
import sz.szsmk.citizencard.model.network.bean.request.QueryCollectedStandreq;
import sz.szsmk.citizencard.model.network.bean.request.QueryUserCardRequest;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryNearStandbyRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardRes;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThiedReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.req.QueryDzsmkAgreementReq;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealName2Res;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.IBusSiteCollectContact;
import sz.szsmk.citizencard.mvp.contract.ICardListCardsContact;
import sz.szsmk.citizencard.mvp.contract.IChargeContact;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback;
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource;
import sz.szsmk.citizencard.retrofitrxjava.newversion.NewHttpApi;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/11/15 9:52
 * description:
 */
public class ChargePresenter extends IBasePresenter
implements IChargeContact.IChargePresenter<IChargeContact.IChargeView> {


    private NetworkDateSources mNetworkDateSource;
    GsdxNetApi gsdxNetApi;

    @Inject
    public ChargePresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDate = NetworkDateSources.getInstance();
        this.mNetworkDateSource = NetworkDateSources.getInstance();
    }

    @Override
    public void queryUserCard(String origin ) {

        QueryUserCardRequest cardRequest = new QueryUserCardRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        cardRequest.setAccess_token(access_token);
        cardRequest.setType("0");
        cardRequest.setOrigin(origin);
        String json = new Gson().toJson(cardRequest);
        mNetworkDateSource.queryUserCardInfo(cardRequest, new SubscribeResult<QueryUserCardRes>() {
            @Override
            protected void onOk(QueryUserCardRes response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "queryUserCard----->" + json);
                ((IChargeContact.IChargeView)mView).getDataListSucc(response);
            }

            @Override
            protected void onFailure(QueryUserCardRes response) {
                super.onFailure(response);
                ((IChargeContact.IChargeView)mView).getDataListFail();

            }

            @Override
            protected void onNext(QueryUserCardRes response) {
                super.onNext(response);
                ((IChargeContact.IChargeView)mView).getDataListFail();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((IChargeContact.IChargeView)mView).getDataListFail();
            }
        });
    }
    private NetworkDateSources mNetworkDate;
    private GetOpenIdRes getOpenIdRes;


    public void getOpenId() {

        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(access_token);
        String s = new Gson().toJson(getOpenIdReq);
        L.e(Constant.TAG, "getOpenid----" + s);
        gsdxNetApi.getOpenId(getOpenIdReq)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribers<GetOpenIdRes>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    protected void _onNext(GetOpenIdRes response) {
                        getOpenIdRes = response;
                        String json = new Gson().toJson(response);
                        L.e(Constant.TAG, "getOpenId---->" + json);
                        String openId = response.getOpenId();
                        ACache.get(DaggerApplication.getIns()).remove("openId");
                        ACache.get(DaggerApplication.getIns()).put("openId", openId + "");
                        ACache.get(DaggerApplication.getIns()).put("userId", response.getUserId() + "");
                        PreAuthResult preAuthResult = new PreAuthResult();
                        preAuthResult.setOpenId(response.getOpenId());
                        GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                        String openId1 = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult().getOpenId();
                        if (response.getCode().equals("000000")) {
//                            ((IChargeContact.IChargeView)mView).getOpenIdSucc();
                            checkIsOpenElecCard(openId);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        Log.e("zdh", "请求失败" + message);
                    }
                });
    }

    public void checkIsOpenElecCard(String openId) {
        CommonRequest request = new CommonRequest();
        request.setOpenId(openId);
        ObjectSignatureUtil.signaturePreAuthRequest(request);
        String toJson = new Gson().toJson(request);
        L.e(Constant.TAG, "checkIsRealName------>" + toJson);

        addSubscription(Objects.requireNonNull(HttpDateSource.INSTANCE.createApi(NewHttpApi.class, Constant.DZ_BASE_URL).
                checkIsRealName(request)),new ApiCallback<CheckIsRealName2Res>(){
                    @Override
                    public void onFailure(@Nullable BaseBean model, @Nullable Throwable e) {

                    }

                    @Override
                    public void onSuccess(@Nullable CheckIsRealName2Res preAuthRes) {
                        String json = new Gson().toJson(preAuthRes);
                        L.e(Constant.TAG, "--------------------" + json);
                        if (preAuthRes.getCode().equals("0000")) {
                            CheckIsRealNameRes checkIsRealNameRes = new CheckIsRealNameRes();
                            CheckIsRealNameRes.DataBean bean = new CheckIsRealNameRes.DataBean();
                            bean.setIsRealName(preAuthRes.getData().getIsRealName());
                            checkIsRealNameRes.setData(bean);
                            queryDzsmkAgreement(openId);
                        } else {
                            PubUtils.popTipOrWarn(DaggerApplication.getIns(),preAuthRes.getMessage() );
                        }
                    }
                }

        );
    }

    public void queryDzsmkAgreement(final String openId) {

        QueryDzsmkAgreementReq queryDzsmkAgreementReq = new QueryDzsmkAgreementReq();
        queryDzsmkAgreementReq.setOpenId(openId);
        queryDzsmkAgreementReq.setUserType(0);
        String json = new Gson().toJson(queryDzsmkAgreementReq);
        L.e(Constant.TAG, "queryDzsmkAgreement---->" + json);

        mNetworkDate.queryDzsmkAgreement(queryDzsmkAgreementReq, new SubscribeResult<QueryDzsmkAgreeMentRes>() {
            @Override
            protected void onOk(QueryDzsmkAgreeMentRes response) {
                String toJson = new Gson().toJson(response);
                String channelId = response.getChannelId();
                ACache.get(DaggerApplication.getIns()).put("channelId", channelId);
                L.e(Constant.TAG, "queryDzsmkAgreement---->" + toJson);
                preAuthThird(openId, "2");

            }

            @Override
            protected void onFailure(QueryDzsmkAgreeMentRes response) {
                super.onFailure(response);
                if (response.getCode().equals("000005")) {
                    ACache.get(DaggerApplication.getIns()).put("channelId", "000003");
                    preAuthThird(openId, "2");
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void preAuthThird(String openId, final String id) {
        PreAuthThiedReq preAuthThiedReq = new PreAuthThiedReq();
        preAuthThiedReq.setMobileNumber(getOpenIdRes.getMobile() + "");
        preAuthThiedReq.setOpenId(openId);
        preAuthThiedReq.setUserId(getOpenIdRes.getUserId() + "");
        preAuthThiedReq.setPhotoUrl("");
        String channelId = ACache.get(DaggerApplication.getIns()).getAsString("channelId");
        preAuthThiedReq.setChannelId(channelId);

        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq);
        String toJson = new Gson().toJson(preAuthThiedReq);

        addSubscription(Objects.requireNonNull(HttpDateSource.INSTANCE.createApi(NewHttpApi.class, Constant.DZ_BASE_URL).
                preAuthThird(preAuthThiedReq)), new ApiCallback<PreAuthThirdRes>() {
            @Override
            public void onSuccess(@Nullable PreAuthThirdRes preAuthRes) {
                String code = preAuthRes.getCode();
                if (code.equals("0000")) {
                    PreAuthThirdRes.DataBean data = preAuthRes.getData();
                    String json = new Gson().toJson(data);
                    ACache.get(DaggerApplication.getIns()).put("token", preAuthRes.getData().getToken());
                    PreAuthResult preAuthResult = new Gson().fromJson(json, PreAuthResult.class);
                    GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                    PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
                    String token = authResult.getToken();
                    ((IChargeContact.IChargeView)mView).getOpenIdSucc();
                    L.e(Constant.MTAG, "存储的token：" + token);

                } else {
                }

            }

            @Override
            public void onFailure(@Nullable BaseBean model, @Nullable Throwable e) {

            }
        });

    }


}
